package net.xdclass.forum.controller;

import net.xdclass.forum.domain.Reply;
import net.xdclass.forum.domain.Topic;
import net.xdclass.forum.domain.User;
import net.xdclass.forum.dto.PageDTO;
import net.xdclass.forum.service.ReplyService;
import net.xdclass.forum.service.TopicService;
import net.xdclass.forum.service.impl.ReplyServiceImpl;
import net.xdclass.forum.service.impl.TopicServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet(name = "replyServlet", urlPatterns = {"/reply"})
public class ReplyServlet extends BaseServlet {
    private static final int pageSize = 2;
    private ReplyService replyService = new ReplyServiceImpl();
    private TopicService topicService = new TopicServiceImpl();

    /**
     * 查询回复列表接口
     * @param req
     * @param resp
     */
    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int topicId = Integer.parseInt(req.getParameter("topic_id"));
        int page = 1;
        String currentpage = req.getParameter("page");

        if (currentpage != null && !"".equals(currentpage)){
            page = Integer.parseInt(currentpage);
        }

        //处理浏览量，若同一个session内只算一次
        String sessionKey = "is_read_"+topicId;
        Boolean isRead = (Boolean) req.getSession().getAttribute(sessionKey);
        if (isRead == null){
            req.getSession().setAttribute(sessionKey,true);
            // 增加一次Pv
            topicService.addOnePv(topicId);
        }

        PageDTO<Reply> replyPageDTO = replyService.findReply(topicId, page, pageSize);
        Topic topic = topicService.findTopicById(topicId);
        System.out.println(replyPageDTO.toString());
        req.setAttribute("replyPage",replyPageDTO);
        req.setAttribute("topic",topic);
        req.getRequestDispatcher("/topic_detail.jsp").forward(req,resp);
    }

    /**
     * 盖楼回复接口
     * @param req
     * @param resp
     */
    public void replyByTopicId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute("loginUser");
        if (user == null) {
            req.setAttribute("msg", "请登录~");
            // 页面跳转
            resp.sendRedirect("/user/login.jsp");
            return;
        }
        int topicId = Integer.parseInt(req.getParameter("topic_id"));
        String content = req.getParameter("content");

        int rows = replyService.replyByTopicId(user, topicId, content);

        // 盖楼回复主题成功
        resp.sendRedirect("/reply?method=list&topic_id="+topicId+"&page=1");

    }
}
